<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 学生个人信息主页
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <!--                <el-select v-model="query.tid" placeholder="教师编号" class="handle-select mr10">-->
        <!--                    <el-option key="001" label="001" value="001"></el-option>-->
        <!--                    <el-option key="002" label="002" value="002"></el-option>-->
        <!--                    <el-option key="003" label="003" value="003"></el-option>-->
        <!--                </el-select>-->
        <el-input v-model="query.number" placeholder="学生学号" class="handle-input mr10"></el-input>
        <el-input v-model="query.name" placeholder="学生姓名" class="handle-input mr10"></el-input>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      </div>

      <div class="handle-right">
          <el-button type="primary" icon="el-icon-plus" @click="createForm">增加</el-button>
      </div>

      <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
        <el-table-column type="index" label="序号" width="55" align="center" :index="indexAdd"></el-table-column>
        <el-table-column prop="name" label="学生姓名" align="center"></el-table-column>
        <el-table-column prop="sex" label="性别" align="center"></el-table-column>
        <el-table-column prop="number" label="学号" align="center"></el-table-column>
        <el-table-column prop="classNo" label="班级" align="center"></el-table-column>
        <el-table-column prop="dormitory" label="宿舍" align="center"></el-table-column>
        <el-table-column prop="admissionTime" label="入学时间" align="center"  width="200%"></el-table-column>
        <el-table-column prop="phone" label="电话" align="center"  width="150%"></el-table-column>
        <el-table-column prop="parentsPhone" label="家长电话" align="center" width="150%"></el-table-column>
        <el-table-column prop="address" label="家庭住址" align="center" :show-overflow-tooltip="true" width="200%">
        </el-table-column>
        <el-table-column prop="post" label="职务" align="center"></el-table-column>
        <el-table-column prop="isPartyMember" label="是否党员" align="center"></el-table-column>
        <el-table-column prop="isPoorStudent" label="是否贫困生" align="center"></el-table-column>
        <el-table-column prop="isSpecialStudent" label="是否特殊学生" align="center" width="150%"></el-table-column>
        <el-table-column prop="remark" label="备注" align="center"></el-table-column>

        <!--                <el-table-column label="账户余额">-->
        <!--                    <template #default="scope">￥{{ scope.row.money }}</template>-->
        <!--                </el-table-column>-->
        <!--                <el-table-column label="头像(查看大图)" align="center">-->
        <!--                    <template #default="scope">-->
        <!--                        <el-image class="table-td-thumb" :src="scope.row.thumb" :preview-src-list="[scope.row.thumb]">-->
        <!--                        </el-image>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->
        <!--                <el-table-column prop="address" label="地址"></el-table-column>-->
        <!--                <el-table-column label="状态" align="center">-->
        <!--                    <template #default="scope">-->
        <!--                        <el-tag :type="-->
        <!--                                scope.row.sex === '成功'-->
        <!--                                    ? 'success'-->
        <!--                                    : scope.row.sex === '失败'-->
        <!--                                    ? 'danger'-->
        <!--                                    : ''-->
        <!--                            ">{{ scope.row.state }}</el-tag>-->
        <!--                    </template>-->
        <!--                </el-table-column>-->

        <!--                <el-table-column prop="date" label="注册时间"></el-table-column>-->
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button type="text" icon="el-icon-delete" class="red"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background layout="total, prev, pager, next" :current-page="query.pageNum"
                       :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
      </div>
    </div>

    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" v-model="editVisible" width="40%" >
      <el-form  ref="formRef" :model="form" :rules="editRules" label-width="120px">
        <el-form-item label="学生姓名" prop="name">
          <el-input  v-model="form.name" type="text" placeholder="请输入用户名" ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" type="text"  placeholder="请选择">
            <el-option key="男" label="男" value="男"></el-option>
            <el-option key="女" label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学号" prop="number">
          <el-input v-model="form.number" type="text" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="classNo">
          <el-input v-model="form.classNo" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="宿舍" prop="dormitory">
          <el-input v-model="form.dormitory" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="入学时间" prop="admissionTime">
          <el-date-picker
              v-model="form.admissionTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="家长电话" prop="parentsPhone">
          <el-input v-model="form.parentsPhone" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="form.address" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="职务" prop="post">
          <el-select v-model="form.post" placeholder="请选择">
            <el-option key="班长" label="班长" value="班长"></el-option>
            <el-option key="团支书" label="团支书" value="团支书"></el-option>
            <el-option key="学习委员" label="学习委员" value="学习委员"></el-option>
            <el-option key="生活委员" label="生活委员" value="生活委员"></el-option>
            <el-option key="文体委员" label="文体委员" value="文体委员"></el-option>
            <el-option key="其他" label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否党员" prop="isPartyMember">
          <el-select v-model="form.isPartyMember" placeholder="请选择">
            <el-option key="是" label="是" value="是"></el-option>
            <el-option key="否" label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否贫困生" prop="isPoorStudent">
          <el-select v-model="form.isPoorStudent" placeholder="请选择">
            <el-option key="是" label="是" value="是"></el-option>
            <el-option key="否" label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否特殊学生" prop="isSpecialStudent" >
          <el-select v-model="form.isSpecialStudent" placeholder="请选择">
            <el-option key="是" label="是" value="是"></el-option>
            <el-option key="否" label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
      </template>
    </el-dialog>


    <!-- 新建弹出框 -->
    <el-dialog title="新建" v-model="addVisible" width="40%">
      <el-form ref="formRef" :model="form" :rules="editRules" label-width="120px">
        <el-form-item label="学生姓名" prop="name">
          <el-input  v-model="form.name" type="text" placeholder="请输入用户名" ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" type="text"  placeholder="请选择">
            <el-option key="男" label="男" value="男"></el-option>
            <el-option key="女" label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学号" prop="number">
          <el-input v-model="form.number" type="text" placeholder="请输入学号"></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="classNo">
          <el-input v-model="form.classNo" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="宿舍" prop="dormitory">
          <el-input v-model="form.dormitory" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="入学时间" prop="admissionTime">
          <el-date-picker
              v-model="form.admissionTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="家长电话" prop="parentsPhone">
          <el-input v-model="form.parentsPhone" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input v-model="form.address" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
        <el-form-item label="职务" prop="post">
          <el-select v-model="form.post" placeholder="请选择">
            <el-option key="班长" label="班长" value="班长"></el-option>
            <el-option key="团支书" label="团支书" value="团支书"></el-option>
            <el-option key="学习委员" label="学习委员" value="学习委员"></el-option>
            <el-option key="生活委员" label="生活委员" value="生活委员"></el-option>
            <el-option key="文体委员" label="文体委员" value="文体委员"></el-option>
            <el-option key="其他" label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否党员" prop="isPartyMember">
          <el-select v-model="form.isPartyMember" placeholder="请选择">
            <el-option key="是" label="是" value="是"></el-option>
            <el-option key="否" label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否贫困生" prop="isPoorStudent">
          <el-select v-model="form.isPoorStudent" placeholder="请选择">
            <el-option key="是" label="是" value="是"></el-option>
            <el-option key="否" label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否特殊学生" prop="isSpecialStudent">
          <el-select v-model="form.isSpecialStudent" placeholder="请选择">
            <el-option key="是" label="是" value="是"></el-option>
            <el-option key="否" label="否" value="否"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="text" placeholder="请输入:"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="create">确 定</el-button>
                </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from 'axios';
import qs from 'qs';
import moment from 'moment';

export default {
  name: "student",
  data() {
    return {
      pageParams: {
        pageNum: 1, // 查询第一页
        pageSize: 10 // 每页10条
      },
    };
  },
  setup() {
    const role = localStorage.getItem("ms_power");
    const query = reactive({
      name: "",
      number: "",
      pageNum: 1,
      pageSize:10
    });
    const tableData = ref([]);
    const pageTotal = ref(0);
    const result = ref();
    // 获取表格数据
    const getData = () => {
      axios.get('ks/student/selectAll', {
        params: {
          pageNum: query.pageNum,
          pageSize: query.pageSize,
          number:query.number,
          name:query.name
        }
      }).then(result => {
        tableData.value = result.data.result.list;
        pageTotal.value = result.data.result.total || 0;
        console.log('value:', result);
        console.log('list:', result.data.result.list);
        console.log('pageTotal:', result.data.result.total);
      }).catch(err => {
        console.error(err)
      })


    };
    getData();

    // 查询操作
    const handleSearch = () => {
      query.pageNum = 1;
      getData();
    };
    // 分页导航
    const handlePageChange = (val) => {
      query.pageNum = val;
      getData();

    };
    //序号连续
    const indexAdd = (index) => {
      //  console.log("indexAdd:index=", index);
      const page = query.pageNum // 当前页码
      const pageSize = query.pageSize // 每页条数
      return index + 1 + (page - 1) * pageSize
    }
    //监听二次删除是否确定
    const isDelete =(number) => {
      ElMessageBox.confirm("确定要删除吗？", "提示", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning"
      }).then((result) => {
        //传入tid进行删除
        const data = {
          number:number,
        }
        console.log("删除-tid = ",number);
        axios.post('ks/student/deleteByNumber',
            qs.stringify(data),
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
        ).then((result) => {
          if(result.data.success) {
            ElMessage.success(`删除第 ${idx + 1} 行成功`);
          } else {
            ElMessage.error("删除失败 : 学号查找不到或者为空");
          }
          getData();
        });


      }).catch(() => {
        ElMessage.info({message: '已取消删除'});
        getData();
      });

    };
    //格式化时间
    const momentData =(form) =>{
      form.admissionTime = moment(form.admissionTime).format('YYYY-MM-DD HH:mm:ss')
    }


    // 删除操作
    const handleDelete = (index,row) => {
      idx = index;
      Object.keys(form).forEach((item) => {
        form[item] = row[item];
      });
      if(role !== "1") {
        isDelete(form.number);
      } else {
        ElMessage.error("啊偶、管理员无权限删除业务数据");
        return;
      }
      tableData.value.splice(index, 1);

    };

    // 表格编辑时弹窗和保存
    const editVisible = ref(false);
    const addVisible = ref(false);
    const createForm= () =>{
      addVisible.value = true;
      Object.keys(form).forEach((item) => {
        form[item] = '';
      });
    }
    const form = reactive({
      id:"",
      name: "",
      sex:"",
      number:"",
      classNo:"",
      dormitory:"",
      admissionTime:"",
      phone:"",
      parentsPhone:"",
      address:"",
      post:"",
      remark:"",
      isPartyMember:"",
      isPoorStudent:"",
      isSpecialStudent:"",

    });
    const validatePhone = (rule, value, callback) => {
      try {
        if (!value) {
          return new Error("请输入电话号码");
        } else
        {
          const reg = /^1[2|3|4|5|6|7|8|9][0-9]\d{8}$/;
          const isPhone = reg.test(value);
          value = Number(value); //转换为数字
          if (typeof value === "number" && !isNaN(value)) {//判断是否为数字
            value = value.toString(); //转换成字符串
            if (value.length < 0 || value.length > 12 || !isPhone) { //判断是否为11位手机号
              callback(new Error("手机号码格式如:138xxxx8754"));
            } else {
              callback();
            }
          } else {
            callback(new Error("手机号格式不对"));
          }
        }
      } catch (err) {
        this.$message.error(err.message)
      }
    }
    //长度校验
    const checkLength = (rule, value, callback) => {
      if (value.length > 200) {
        callback(new Error('描述不能超过200字符'));
      } else {
        callback();
      }
    };
    // 定义校验规则
    const editRules = reactive({
      name: [
        { required: true, message: "用户名不能为空" , trigger: 'blur' },
        { validator: checkLength, trigger: "blur" }
      ],
      sex : [
        { required: true, message: '请选择', trigger: 'blur' }
      ],
      number: [
        { required: true, message: '学生学号不能为空', trigger: 'blur' },
        { validator: checkLength, trigger: "blur" }
      ],
      classNo: [
        { required: true, message: '班级不能为空', trigger: 'blur' },
        { validator: checkLength, trigger: "blur" }
      ],
      dormitory: [
        { required: true, message: '宿舍号不能为空', trigger: 'blur' }
      ],
      admissionTime: [
        { required: true, message: '请选择时间', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { validator: validatePhone, trigger: "blur" }
      ],
      parentsPhone: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { validator: validatePhone, trigger: "blur" }
      ],
      address: [
        { required: true, message: '请输入家庭地址', trigger: 'blur' },
        { validator: checkLength, trigger: "blur" }
      ],
      isPartyMember: [
        { required: true, message: '请选择', trigger: 'blur' }
      ],
      isPoorStudent: [
        { required: true, message: '请选择', trigger: 'blur' }
      ],
      isSpecialStudent: [
        { required: true, message: '请选择', trigger: 'blur' }
      ],
      post: [
        { required: true, message: '请选择', trigger: 'blur' }
      ]
    })

    let idx = -1;
    const handleEdit = (index, row) => {
      idx = index;
      Object.keys(form).forEach((item) => {
        form[item] = row[item];
      });
      if(role !== "1") {
        editVisible.value = true;
      } else {
        ElMessage.error("啊偶、管理员无权限更新业务数据");
        return;
      }

    };
    //todo
    const formRef = ref(null);
    const saveEdit = () => {
      //表单校验
      console.log("form为:",form)
      formRef.value.validate((valid) => {
        if (valid) {
          console.log("编辑--表单校验:",form);
          momentData(form);
          console.log("编辑--表单time:",form.admissionTime);
          axios.post('ks/student/update', form)
              .then((result)=>{
                    editVisible.value = false;
                    if(result.data.success) {
                      ElMessage.success(`修改第 ${idx + 1} 行成功`);
                    } else {
                      ElMessage.error(result.data.message+ ': 学生学号已存在 或 数据格式不正确');
                    }
                getData();
                  }
              )
        } else {
          ElMessage.error("提交失败");
          getData();
        }
      });
      Object.keys(form).forEach((item) => {
        tableData.value[idx][item] = form[item];
      });

    };

    const create = () => {
      formRef.value.validate((valid) => {
        if (valid) {
          console.log("新增--表单校验:", form);
          momentData(form);
          console.log("新增--表单时间:", form.admissionTime);
          axios.post('ks/student/save', form)
              .then((result) => {
                    addVisible.value = false;
                    if (result.data.success) {
                      ElMessage.success(`添加成功`);
                    } else {
                      ElMessage.error(result.data.message + ': 学生学号已存在 或 数据格式不正确');
                    }
                getData();
                  }
              )
        } else {
          ElMessage.error("提交失败");
          getData();
        }
      });
    };


    return {
      query,
      tableData,
      pageTotal,
      editVisible,
      form,
      editRules,
      addVisible,
      formRef,
      result,
      role,
      momentData,
      checkLength,
      isDelete,
      validatePhone,
      createForm,
      handleSearch,
      handlePageChange,
      handleDelete,
      handleEdit,
      saveEdit,
      create,
      indexAdd
    };
  },
};
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}
.handle-right {
  margin-bottom: 20px;
  float:right;
}
.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
